{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e12a771",
   "metadata": {
    "language_info": {
     "name": "polyglot-notebook"
    },
    "polyglot_notebook": {
     "kernelName": "csharp"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello from the new thread!\n",
      "Main thread finished.\n"
     ]
    }
   ],
   "source": [
    "using System.Threading;\n",
    "\n",
    "void ThreadFunc() {\n",
    "    // 线程要执行的代码\n",
    "    Console.WriteLine(\"Hello from the new thread!\");\n",
    "}\n",
    "\n",
    "// 1. 申明一个新的线程,需要将线程执行的代码封装到一个函数中\n",
    "Thread thread = new Thread(new ThreadStart(ThreadFunc));\n",
    "// 2. 启动线程\n",
    "thread.Start();\n",
    "// 3. 设置为后台线程: 当前台线程都结束了,整个程序结束了,即使还有后台线程正在运行,也会被强制结束. 如果不设置后台线程,可能导致线程无法正常结束,线程还在运行,主线程无法正常结束\n",
    "thread.IsBackground = true;\n",
    "// 4. 关闭线程\n",
    "// thread.Abort(); // 线程中提供的方法,在.Net core 中无法使用\n",
    "thread = null; // 关闭线程\n",
    "// 5. 线程休眠\n",
    "Thread.Sleep(1000); // 让主线程休眠1秒\n",
    "Console.WriteLine(\"Main thread finished.\");\n",
    "// 6. 线程之间共享数据,线程安全lock(引用类型对象){}\n",
    "private static readonly object _lock = new object();\n",
    "\n",
    "void ThreadSafeMethod() {\n",
    "    lock (_lock) {\n",
    "        // 线程安全的代码\n",
    "    }\n",
    "}"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".NET (C#)",
   "language": "C#",
   "name": ".net-csharp"
  },
  "language_info": {
   "name": "polyglot-notebook"
  },
  "polyglot_notebook": {
   "kernelInfo": {
    "defaultKernelName": "csharp",
    "items": [
     {
      "aliases": [],
      "name": "csharp"
     }
    ]
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
